package cn.samler.shopapi.Utils;

import cn.samler.shopapi.Config.BmobConfig;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Slf4j
@Component
public class BmobSMSUtils {
    private static BmobSMSUtils ins = null;
    private final BmobConfig config;

    private BmobSMSUtils(BmobConfig config) {
        this.config = config;
    }

    @PostConstruct
    private void init() {
        ins = new BmobSMSUtils(this.config);
    }

    public static BmobSMSUtils getInstance() {
        return ins;
    }

    private JSONObject request(String path, JSONObject obj) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost http;
        CloseableHttpResponse resp = null;
        try {
            http = new HttpPost(this.config.getApiUrl() + path);
            http.setHeader("X-Bmob-Application-Id", this.config.getAppId());
            http.setHeader("X-Bmob-REST-API-Key", this.config.getApiKey());
            http.setHeader("Content-Type", "application/json");

            http.setEntity(new StringEntity(obj.toJSONString(), "utf-8"));
            resp = httpclient.execute(http);

            HttpEntity entity = resp.getEntity();
            if (entity != null)
                return JSON.parseObject(EntityUtils.toString(entity));
        } catch (Exception e) {
            log.error("BmobSMS request exception: " + e);
        } finally {
            try {
                if (resp != null) resp.close();
            } catch (Exception e) {
                log.error("BmobSMS response close exception: " + e);
            }
        }

        return null;
    }

    /**
     * 发送一条验证短信
     *
     * @param tel 目标手机号码
     * @return success or not
     */
    public boolean send(String tel) {
        JSONObject json = new JSONObject();
        json.put("mobilePhoneNumber", tel);
        json.put("template", this.config.getTemplateName());
        JSONObject result = this.request("requestSmsCode", json);
        if (result != null && result.getOrDefault("smsId", null) != null)
            return true;

        log.warn("验证码发送异常：" + (result != null ? result.getOrDefault("error", null) : "request null"));
        return false;
    }

    /**
     * 短信验证码校验
     *
     * @param tel   目标手机号
     * @param vCode 客户端输入的验证码
     * @return access or not
     */
    public boolean verify(String tel, String vCode) {
        JSONObject json = new JSONObject();
        json.put("mobilePhoneNumber", tel);
        JSONObject result = this.request("verifySmsCode/" + vCode, json);
        if (result != null && "ok".equals(result.getOrDefault("msg", null)))
            return true;

        log.warn("验证码验证异常：" + (result != null ? result.getOrDefault("error", null) : "request null"));
        return false;
    }
}
